﻿/* -----------------------------------------------------------------------------
 * <copyright file="OPWorkEfficiencyQueryControl.xaml.cs" company="O-RID">
 *     Copyright (c)2010 O-RID Co.,Ltd.
 * </copyright>
 * <author>Zhang jun</author>
 * <summary>
 *           UNIT 稼働率查询
 *     引用服务： WCFServers.UnitQueryRef
 *     服务功能： 通过调用服务端的存储过程，来实现查询服务
 *    
 *     引用服务：WCFLog4Ref.WCFLog4Client
 *     服务功能：记录日志
 *       
 *      作成日：07/14/2010 
 *              08/11/2010 -- 增加导出功能
 *              09/28/0210 增加 分页记录数可自定义
 *              10/14/2010 修改 导出功能异常
 *              10/18/2010 修改 点击标题头排序时，导出内容不是排序结果的问题。
 * </summary>
 * -----------------------------------------------------------------------------
 */

namespace Orid.Management.Statistics.OperatorUnitMangement.EfficiencyRelated.UnitWorkEfficiencyQuery
{
    using System;
    using System.Threading;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Media;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.Export;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.FunctionList;
    using Orid.Management.Statistics.OperatorUnitMangement.Common.SearchCtrl;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFLog4Ref;
    using Orid.Management.Statistics.OperatorUnitMangement.WCFServers.UnitQueryRef;
    using childWindow = Orid.Management.Statistics.OperatorUnitMangement.Common.Window;
    using Command = Orid.Management.Statistics.OperatorUnitMangement.Command;
    using Wcf = Orid.Management.Statistics.OperatorUnitMangement.Common.Service;


    /// <summary>
    ///  UNIT 稼働率查询
    /// </summary>
    public partial class UnitWorkEfficiencyQueryControl : UserControl
    {
        #region 全局变量

        /// <summary>
        /// 当前查询框的名字（日志用）
        /// </summary>
        private string ctrlName = "UNIT稼働率 ";

        /// <summary>
        /// 查询区域对象
        /// USEfficSelContainer
        /// </summary>
        private USEfficSelContainer efficSelContainer;

        /// <summary>
        /// 消息提示子窗体
        /// errorMessbox
        /// </summary>
        private childWindow.MessageBox errorMessbox;

        /// <summary>
        /// 日志服务定义
        /// WCFLog4Client
        /// </summary>
        private WCFLog4Client wcfLogClient;

        /// <summary>
        /// 分页控件
        /// PagedCollectionView
        /// </summary>
        private PagedCollectionView pcv;

        /// <summary>
        /// 存放导出数据
        /// </summary>
        /// <value> 08/11/2010  ADD </value>
        private DataGrid dataToCSV = null;

        /// <summary>
        /// 记录是小时别/天别 稼动率（用于记录日志）
        /// </summary>
        /// <value> 08/11/2010  ADD </value>
        private string logTag = null;

        /// <summary>
        /// 记录总数
        /// </summary>
        /// <value>10/18/2010 Add 排序导出用</value>
        private int sumRecordCount = 0;

        /// <summary>
        /// 记录NumericUpDown分页数
        /// </summary>
        /// <value>10/18/2010 Add 排序导出用</value>
        private double oldNumericUpDown = 0;


        #endregion 全局变量

        /// <summary>
        /// 构造函数
        /// </summary>
        public UnitWorkEfficiencyQueryControl(USEfficSelContainer efficSelContainer)
        {
            InitializeComponent();

            // 引用主题
            ((App)Application.Current).SetTheme((Grid)LayoutRoot);

            this.dgUNITWorkEfficiencyQueryDay.HeadersVisibility = DataGridHeadersVisibility.All;//同时显示DataGrid的行头与列头
            this.dgUNITWorkEfficiencyQueryHour.HeadersVisibility = DataGridHeadersVisibility.All;//同时显示DataGrid的行头与列头

            this.InitField();

            this.efficSelContainer = efficSelContainer;
            #region 查询按钮设置
            Command.UNIT.UnitWorkEfficiencyQuery queryCommand = new Command.UNIT.UnitWorkEfficiencyQuery(efficSelContainer);

            queryCommand.ExecOver -= new EventHandler<SelectUNITWorkEfficiencyInforCompletedEventArgs>(this.WCFUNITWorkEfficiencyQueryClient_SelectUNITWorkEfficiencyCompleted);
            queryCommand.ExecBegin -= new EventHandler<EventArgs>(this.QueryCommand_ExecBegin);

            queryCommand.ExecOver += new EventHandler<SelectUNITWorkEfficiencyInforCompletedEventArgs>(this.WCFUNITWorkEfficiencyQueryClient_SelectUNITWorkEfficiencyCompleted);
            queryCommand.ExecBegin += new EventHandler<EventArgs>(this.QueryCommand_ExecBegin);

            efficSelContainer.QueryCcommand = queryCommand;
            #endregion 查询按钮设置

            #region 导出设置
            //导出
            Command.DateExport exportCommand = new Command.DateExport();
            //导出开始
            exportCommand.ExecBegin += new EventHandler<EventArgs>(this.ExportCommand_ExecBegin);

            this.efficSelContainer.ExportComand = exportCommand;
            #endregion 导出设置
            

            //设置 查询界面 的 查询按钮/数据导出 初始化可用
            this.efficSelContainer.btnUnitSelect.IsEnabled = true;
            this.efficSelContainer.btnExport.IsEnabled = true;
            this.nuPageSize.IsEnabled = true; //分页数量 09/28/2010 Add

            // 设置背景色
            LayoutRoot.Background = new SolidColorBrush(Color.FromArgb(255, 243, 244, 245));

        }

        /// <summary>
        /// 初始化变量 InitField
        /// </summary>  
        private void InitField()
        {
            this.wcfLogClient = Wcf.Service.Log4;
            this.errorMessbox = new childWindow.MessageBox();
            this.dataToCSV = new DataGrid();
        }

        /// <summary>
        /// 查询开始事件
        /// QueryCommand_ExecBegin
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void QueryCommand_ExecBegin(object sender, EventArgs e)
        {
            this.SetBusyBar(100);
        }

        #region BusyBar
        /// <summary>
        /// 让BusyBar开始
        /// SetBusyBar
        /// </summary>
        /// <param name="busySeconds">busySeconds 单位 ms</param>
        public void SetBusyBar(int busySeconds)
        {
            int delayMilliseconds = 2;
            biBusyBar.DisplayAfter = TimeSpan.FromMilliseconds(delayMilliseconds);

            DataContext = true;
            this.nuPageSize.IsEnabled = false; //分页数量 09/28/2010 Add
            ThreadPool.QueueUserWorkItem((state) =>
            {
                Thread.Sleep(busySeconds * 1000);
            });
        }
        #endregion BusyBar

        #region 稼动率查询(实现)
        /// <summary>
        /// 稼动率查询(实现)
        /// WCFOPWorkEfficiencyQueryClient_SelectOPWorkEfficiencyCompleted
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of RoutedEventArgs</param>
        private void WCFUNITWorkEfficiencyQueryClient_SelectUNITWorkEfficiencyCompleted(object sender, SelectUNITWorkEfficiencyInforCompletedEventArgs e)
        {
            try
            {
                //设置 查询界面 的 查询按钮 初始化可用
                this.efficSelContainer.btnUnitSelect.IsEnabled = true;

                // 稼动率类型
                //string statsticClass = this.selanycontainer. cbWorkEfficiency.SelectedItem.ToString();
                string statsticClass = this.efficSelContainer.cbWorkEfficiency.SelectionBoxItem.ToString();

                if (e.Error == null)
                {
                    if (e.Result.Count > 0)
                    {
                        //记录所查询的记录总数（导出结果与排序内容一致用）
                        this.sumRecordCount = e.Result.Count;

                        this.pcv = new PagedCollectionView(e.Result);
                        this.pcv.PageSize = Convert.ToInt32(this.nuPageSize.Value);

                        Dispatcher.BeginInvoke(() => DataContext = false);
                        this.nuPageSize.IsEnabled = true; //分页数量 09/28/2010 Add

                        if (statsticClass.Trim().ToUpper().Equals("DAY"))
                        {
                            //天稼动率
                            this.dgUNITWorkEfficiencyQueryDay.ItemsSource = this.pcv;
                            this.dgUNITWorkEfficiencyQueryHour.ItemsSource = null;

                            this.dataToCSV.ItemsSource = null;
                            this.dataToCSV.ItemsSource = e.Result;

                            this.bdDay.Visibility = Visibility.Visible;
                            this.bdHour.Visibility = Visibility.Collapsed;
                            //显示哪个固定例
                            this.spDayHour.Visibility = Visibility.Visible;
                            this.nudEfficiencyQueryDay.Visibility = Visibility.Visible;
                            this.nudEfficiencyQueryHour.Visibility = Visibility.Collapsed;
                        }
                        else
                        {
                            //小时 稼动率
                            this.dgUNITWorkEfficiencyQueryDay.ItemsSource = null;
                            this.dgUNITWorkEfficiencyQueryHour.ItemsSource = this.pcv;

                            this.dataToCSV.ItemsSource = null;
                            this.dataToCSV.ItemsSource = e.Result;

                            this.bdDay.Visibility = Visibility.Collapsed;
                            this.bdHour.Visibility = Visibility.Visible;
                            //显示哪个固定例
                            this.spDayHour.Visibility = Visibility.Visible;
                            this.nudEfficiencyQueryDay.Visibility = Visibility.Collapsed;
                            this.nudEfficiencyQueryHour.Visibility = Visibility.Visible;
                        }

                        this.dpDataPage.DataContext = this.pcv;

                        this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr +
                                                        "在 "+this.ctrlName +" 中查询记录" +
                                                        efficSelContainer.WhereIntorLogs );
                    }
                    else
                    {
                        this.dgUNITWorkEfficiencyQueryDay.ItemsSource = null;
                        this.dgUNITWorkEfficiencyQueryHour.ItemsSource = null;
                        this.dpDataPage.DataContext = null;
                        this.dataToCSV.ItemsSource = null;

                        this.bdDay.Visibility = Visibility.Collapsed;
                        this.bdHour.Visibility = Visibility.Collapsed;
                        this.spDayHour.Visibility = Visibility.Collapsed;

                        Dispatcher.BeginInvoke(() => DataContext = false);
                        this.nuPageSize.IsEnabled = true; //分页数量 09/28/2010 Add

                        throw (new Exception(this.ctrlName +" 查询没有结果。"));
                    }
                }
                else
                {
                    Dispatcher.BeginInvoke(() => DataContext = false);
                    this.nuPageSize.IsEnabled = true; //分页数量 09/28/2010 Add

                    throw (new Exception("WCFUNITWorkEfficiencyQueryRef服务返回值有错" + e.Error.Message.ToString()));
                }
            }
            catch (Exception exce)
            {
                Dispatcher.BeginInvoke(() => DataContext = false);
                this.nuPageSize.IsEnabled = true; //分页数量 09/28/2010 Add

                string exceptionStr = FunctionClass.GetMessageInformation(exce);

                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                                ctrlName + "UnitWorkEfficiencyQueryControl" +
                                                exceptionStr +
                                                efficSelContainer.WhereIntorLogs);

                FunctionClass.ShowMessageBox(
                   this.errorMessbox,
                   1,
                   "提示",
                   exceptionStr,
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }
        #endregion 稼动率查询(实现)  
    
        #region 数据导出 08/11/2010 -- ADD --

        /// <summary>
        /// 导出开始
        /// ExportCommand_ExecBegin
        /// </summary>
        /// <param name="sender">sender of object</param>
        /// <param name="e">e type of EventArgs</param>
        private void ExportCommand_ExecBegin(object sender, EventArgs e)
        {
            this.ExportDate();
        }

        /// <summary>
        /// 导出 按钮  
        /// ExportDate
        /// </summary>        
        private void ExportDate()
        {
            try
            {
                //设置 查询界面 的 数据导出 可用
                this.efficSelContainer.btnExport.IsEnabled = true;

                // 天稼动率
                if (this.efficSelContainer.cbWorkEfficiency.SelectionBoxItem.ToString().Trim().ToUpper().Equals("DAY"))
                {
                    this.logTag = string.Empty;
                    this.logTag = " 按天 ";
                    if (this.dgUNITWorkEfficiencyQueryDay.ItemsSource == null)
                    {
                        throw new Exception("请查询后再将数据导出。");
                    }
                    else
                    {
                        //导出结果与排序内容一致用
                        this.oldNumericUpDown = this.nuPageSize.Value;
                        this.pcv.PageSize = this.sumRecordCount;
                        this.dataToCSV.ItemsSource = this.pcv;

                        this.ExportDataToFile(this.dgUNITWorkEfficiencyQueryDay);
                    }
                }
                else  //小时稼动率
                {
                    this.logTag = string.Empty;
                    this.logTag = " 按小时 ";

                    if (this.dgUNITWorkEfficiencyQueryHour.ItemsSource == null)
                    {
                        throw new Exception("请查询后再将数据导出。");
                    }
                    else
                    {
                        //导出结果与排序内容一致用
                        this.oldNumericUpDown = this.nuPageSize.Value;
                        this.pcv.PageSize = this.sumRecordCount;
                        this.dataToCSV.ItemsSource = this.pcv;

                        this.ExportDataToFile(this.dgUNITWorkEfficiencyQueryHour);
                    }
                }
            }
            catch (Exception ex)
            {
                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                                    " ExportDate(" + this.ctrlName +
                                                    this.logTag +
                                                    ") " +
                                                    ex.Message.ToString() +
                                                    efficSelContainer.WhereIntorLogs);
                FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                    "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        /// <summary>
        /// 数据导出
        /// ExportDataToFile
        /// </summary>
        /// <param name="grid">带有显示格式的 grid</param>
        /// <value>10/14/2010 修改 导出功能异常</value>
        private void ExportDataToFile(DataGrid grid)
        {
            try
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.DefaultExt = "csv";
                sfd.Filter = "CSV Files (*.csv)|*.csv|All files (*.*)|*.*";

                sfd.FilterIndex = 1;
                bool? ret = sfd.ShowDialog();
                if (ret == true)
                {
                    string data = DataExport.ExportDataGrid(true, grid, this.dataToCSV, null);

                    using (System.IO.Stream stream = sfd.OpenFile())
                    {
                        using (System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, System.Text.UnicodeEncoding.Unicode))
                        {
                            //由 逗号 换成 ^ ,--07/30/2010--EIDT 修改 千分位分割符用TAB替换问题
                            data = data.Replace("^", "\t");
                            writer.Write(data);
                            writer.Close();
                        }

                        stream.Close();
                    }
                    this.pcv.PageSize = Convert.ToInt32(this.oldNumericUpDown);

                    this.wcfLogClient.InfoAsync(((App)Application.Current).LogStr +
                                                                "在 " + this.ctrlName + "(" +
                                                                this.logTag +
                                                                ") 查询中导出记录" +
                                                                efficSelContainer.WhereIntorLogs);
                    FunctionClass.ShowMessageBox(
                      this.errorMessbox,
                      0,
                     "提示",
                     "数据已导出。",
                     Colors.Gray,
                     true,
                     Visibility.Visible,
                     Visibility.Collapsed);
                    return;
                }
                else
                {
                    this.pcv.PageSize = Convert.ToInt32(this.oldNumericUpDown);
                    return;
                }
            }
            catch (Exception ex)
            {
                this.pcv.PageSize = Convert.ToInt32(this.oldNumericUpDown);

                this.wcfLogClient.ErrorAsync(((App)Application.Current).LogStr +
                                                " ExportDataToFile(" + this.ctrlName +
                                                this.logTag +
                                                ") " +
                                                ex.Message.ToString() +
                                                efficSelContainer.WhereIntorLogs);
                FunctionClass.ShowMessageBox(
                    this.errorMessbox,
                    1,
                   "提示",
                   ex.Message.ToString(),
                   Colors.Gray,
                   true,
                   Visibility.Visible,
                   Visibility.Collapsed);
                return;
            }
        }

        #endregion 数据导出
    }
}
